package com.pansoft.openplanet.activity.child;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.account.model.ActGeneratorBean;
import com.pansoft.openplanet.account.model.BchGeneratorBean;
import com.pansoft.openplanet.account.model.BtcBean;
import com.pansoft.openplanet.account.model.EthBean;
import com.pansoft.openplanet.account.util.ActAccountGenerator;
import com.pansoft.openplanet.account.util.BTCAccountGenerator;
import com.pansoft.openplanet.account.util.BchAccountGenerator;
import com.pansoft.openplanet.account.util.EthAccountGenerator;
import com.pansoft.openplanet.activity.TCBaseActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.CreateChildWalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;

import java.io.File;

import io.reactivex.disposables.Disposable;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 创建子账户钱包
 * Created by will on 18-3-20.
 */

public class CreateChildWalletActivity extends TCBaseActivity implements View.OnClickListener {

    private String TAG = this.getClass().getSimpleName();


    private Button tvCreateWallet;
    private Button tvResotreWallet;
    private ScrollView scrollView;
    private TextView tvTopIntro;//创建您的基地账户/恢复您的基地账户
    private TextView tvMiddleIntro, tvBottomIntro;
    private TextView tvTitle;

    //    //助记词
//    private String mnemonic;
//    //帐号
//    private String address;
//    //数据库
    private AccountDao accountDao;
//    //生成钱包的Account对象
//    private Account account;
//    //密钥
//    private ECKeyPair ecKeyPair;
//    private File keyStoreFile;
//    private String btcPrivKey;//btc私钥

    private int chainId;//钱包类型
    //登录密码
    private String loginPwd;
    private CreateChildWalletBean childWalletBean;
    /** 是否是创建卡片冷钱包 **/
    private boolean isCardColdWallet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_create_child_wallet);
        accountDao = new AccountDao(this);
        isCardColdWallet = getIntent().getBooleanExtra("isCardColdWallet", false);
        initView();
        initOther();
    }


    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_create_wallet_account));
        tvCreateWallet = (Button) findViewById(R.id.tv_create_wallet);
        tvCreateWallet.setOnClickListener(this);
        tvResotreWallet = (Button) findViewById(R.id.tv_restore_wallet);
        tvResotreWallet.setOnClickListener(this);
        scrollView = (ScrollView) findViewById(R.id.scrollview);
        tvTopIntro = (TextView) findViewById(R.id.tv_welcome);
        tvMiddleIntro = (TextView) findViewById(R.id.tv_wallet_intro);
        tvBottomIntro = (TextView) findViewById(R.id.tv_create_hint);
        scrollToShowSubmitBtn(scrollView);
    }


    @Override
    public void onBackPressed() {
        finish();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            onBackPressed();
        } else if (id == R.id.tv_create_wallet) {
//            PassWordAlertDialog dialog = new PassWordAlertDialog(this, new PassWordAlertDialog.OnEnterClick() {
//                @Override
//                public void passVerifySuccess(String passWord) {
//                    loginPwd= passWord;
//
//                }
//            });
//            dialog.show();
            generateWallet();
        }

    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    private void initOther() {
        chainId = getIntent().getIntExtra("chainId", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);
        String walletAvatar = getIntent().getStringExtra("wallet_avatar");
        String walletName = getIntent().getStringExtra("wallet_name");
        childWalletBean = new CreateChildWalletBean.Builder().build();
        childWalletBean.setPhoneNumber(EnvironmentVariable.getUserName());
        childWalletBean.setChainId(chainId);
        childWalletBean.setWalletAvatar(walletAvatar);
        childWalletBean.setWalletName(walletName);
        childWalletBean.setLoginPwd(loginPwd);


    }

    private void generateWallet() {
        showLoading(ResStringUtil.getString(R.string.open_planet_iscreateing));
        //keystore存放的路径
        final String path = TalkChainConstant.getChildAccountFilePath(this) + File.separator + childWalletBean.getPhoneNumber();
        //文件夹不存在，创建文件夹
        final File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }


        if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
            //创建BTC钱包
            createBTCWallet(path);
        } else if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
            //创建eth钱包
            createETHWallet(path,IPAssetsConstant.ChainEnum.ETH);
        } else if (chainId == IPAssetsConstant.CHAIN_ID_ACT) {
            //创建ACT钱包
            createActWallet();
        } else if (chainId == IPAssetsConstant.CHAIN_ID_BCH) {
            //创建Bch钱包
            createBchWallet(path);
        }else if (chainId == IPAssetsConstant.CHAIN_ID_ETE) {
            //创建eth钱包
            createETHWallet(path,IPAssetsConstant.ChainEnum.ETE);
        }

    }

    private void createActWallet() {
        Disposable disposable = ActAccountGenerator.createAccountAsync(new ActAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(ActGeneratorBean actGeneratorBean) {
                dismissLoading();
                childWalletBean.setWalletAddress(actGeneratorBean.getWalletAddress());
                childWalletBean.setMnemonic(actGeneratorBean.getMnemonic());
                childWalletBean.setPublicKey(actGeneratorBean.getPublicKey());
                childWalletBean.setPrivateKey(actGeneratorBean.getPrivateKey());

                //保存到数据库
                Account account = new Account(actGeneratorBean.getWalletAddress(), childWalletBean.getWalletName(), childWalletBean.getWalletAvatar());
                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                account.setPublicKey(actGeneratorBean.getPublicKey());
                account.setSecretPrivateKey(actGeneratorBean.getSecretPriKey());
                account.setMaster(false);
                account.setCurrentShow(false);
                account.setEnable(false);
                account.setBlockChainName(IPAssetsConstant.ChainEnum.ACHAIN.chainName);
                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                accountDao.insertOrReplace(account);
                //显示成功对话框
                showSuccessAlert();
            }

            @Override
            public void generatorFail() {
                dismissLoading();
                showFailAlert(null);
            }
        });
        addDisposable(disposable);
    }

    private void createETHWallet(String path, final IPAssetsConstant.ChainEnum blockChainEnum) {

        Disposable disposable = EthAccountGenerator.createEthAccountAsync(path, new EthAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(EthBean ethBean) {
                dismissLoading();
                String address = ethBean.getEthAddress();
                File keyStoreFile = new File(ethBean.getKeyStoreFilePath());
                String mnemonic = ethBean.getMnemonic();

                childWalletBean.setWalletAddress(address);
                childWalletBean.setMnemonic(mnemonic);
                childWalletBean.setPublicKey(ethBean.getEcKeyPair().getPublicKey().toString());
                childWalletBean.setPrivateKey(ethBean.getEcKeyPair().getPrivateKey().toString());

                //保存到数据库
                Account account = new Account(address, childWalletBean.getWalletName(), childWalletBean.getWalletAvatar());
                account.setFileName(keyStoreFile.getAbsolutePath());
                account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                account.setPublicKey(ethBean.getEcKeyPair().getPublicKey().toString());
                account.setMaster(false);
                account.setCurrentShow(false);
                account.setEnable(false);
                account.setBlockChainName(blockChainEnum.chainName);

                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                accountDao.insertOrReplace(account);
                //显示成功对话框
                showSuccessAlert();
            }

            @Override
            public void generatorFail() {
                dismissLoading();
                showFailAlert(null);
            }
        });

        addDisposable(disposable);
    }

    /**
     * 创建BTC钱包
     */
    private void createBTCWallet(String path) {
        Disposable disposable = BTCAccountGenerator.createBtcAccountAsync(path, new BTCAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(BtcBean btcBean) {
                dismissLoading();
                String address = btcBean.getBtcAddress();
                String mnemonic = btcBean.getMnemonic();

                childWalletBean.setWalletAddress(address);
                childWalletBean.setMnemonic(mnemonic);
                childWalletBean.setPublicKey(btcBean.getBtcPubKey());
                childWalletBean.setPrivateKey(btcBean.getBtcPrivKey());

                Account account = new Account();
                if (!EnvSupportManager.isSupportHDWallet()) {
                    File keyStoreFile = new File(btcBean.getKeyStoreFilePath());
                    account.setFileName(keyStoreFile.getAbsolutePath());
                } else {
                    account.setHdBtcXpub(btcBean.getHdBtcXpub());
                    account.setHdBtcMaxChildIndex(btcBean.getHdBtcMaxChildIndex());
                    account.setHdBtcCurrentChildAddress(btcBean.getHdBtcCurrentChildAddress());
                    childWalletBean.setHdBtcXpub(account.getHdBtcXpub());
                }
                account.setAddress(btcBean.getBtcAddress());
                account.setImUserId(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                account.setAcccountName(childWalletBean.getWalletName());
                account.setAccountAvatar(childWalletBean.getWalletAvatar());
                account.setBlockChainName(IPAssetsConstant.ChainEnum.BTC.chainName);
                // btcPrivKey = btcBean.getBtcPrivKey();
//                account.setSecretPrivateKey(btcBean.getBtcPrivKey());
                account.setPublicKey(btcBean.getBtcPubKey());
                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                account.setSecretMnemonic(btcBean.getSecretMnemonic());
                account.setEnable(false);
                accountDao.insertOrReplace(account);
                showSuccessAlert();
            }

            @Override
            public void generatorFail() {
                dismissLoading();
                showFailAlert(null);
            }
        });
        addDisposable(disposable);
    }

    /**
     * 创建BCH钱包
     */
    private void createBchWallet(String path) {
        Disposable disposable = BchAccountGenerator.createBtcAccountAsync(path, new BchAccountGenerator.GeneratorListener() {
            @Override
            public void generatorSuccess(BchGeneratorBean ethBean) {

                dismissLoading();

                String address = ethBean.getWalletAddress();
                File keyStoreFile = new File(ethBean.getKeyStoreFilePath());
                String mnemonic = ethBean.getMnemonic();

                childWalletBean.setWalletAddress(address);
                childWalletBean.setMnemonic(mnemonic);
                childWalletBean.setPublicKey(ethBean.getPublicKey());
                childWalletBean.setPrivateKey(ethBean.getPrivateKey());

                Account account = new Account();
                account.setAddress(ethBean.getWalletAddress());
                account.setImUserId(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                account.setAcccountName(childWalletBean.getWalletName());
                account.setAccountAvatar(childWalletBean.getWalletAvatar());
                account.setBlockChainName(IPAssetsConstant.ChainEnum.BCH.chainName);
                // btcPrivKey = ethBean.getBtcPrivKey();
//                account.setSecretPrivateKey(ethBean.getBtcPrivKey());
                account.setPublicKey(ethBean.getPublicKey());
                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress", ""));
                account.setSecretMnemonic(ethBean.getSecretMnemonic());

                account.setFileName(keyStoreFile.getAbsolutePath());
                account.setEnable(false);
                accountDao.insertOrReplace(account);
                showSuccessAlert();
            }

            @Override
            public void generatorFail() {
                dismissLoading();
                showFailAlert(null);
            }
        });
        addDisposable(disposable);
    }


    private void showFailAlert(String message) {
        if (message == null)
            message = ResStringUtil.getString(R.string.open_planet_create_fail_please_retry);
        new AlertDialog.Builder(CreateChildWalletActivity.this)
                .setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        generateWallet();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, null)
                .create()
                .show();
    }

    private void showSuccessAlert() {
        new AlertDialog.Builder(CreateChildWalletActivity.this)
                .setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.openplanet_jidi_create_success))
                .setPositiveButton(ResStringUtil.getString(R.string.openplanet_goback), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        Intent intent = new Intent(CreateWalletConfirm.this, BackupWalletActivity.class);
                        Intent intent = new Intent(CreateChildWalletActivity.this, BackupChildMnemonicActivity.class);
//                        intent.putExtra("chainId", chainId);
//                        intent.putExtra("wallet_avatar", walletAvatar);
//                        intent.putExtra("wallet_name", walletName);
//                        intent.putExtra("number", number);
//                        intent.putExtra("mnemonic", mnemonic);//助记词
//                        if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
//                            intent.putExtra("address", account.getAddress());
//                            intent.putExtra("ethPublicKey", account.getPublicKey());
//                            intent.putExtra("ethPrivateKey", btcPrivKey);
//                        } else {
//                            intent.putExtra("address", address);
//                            intent.putExtra("ethPublicKey", ecKeyPair.getPublicKey().toString());
//                            intent.putExtra("ethPrivateKey", ecKeyPair.getPrivateKey().toString());
//                        }
                        intent.putExtra("isCardColdWallet", isCardColdWallet);
                        intent.putExtra("childWalletBean", childWalletBean);
                        startActivity(intent);
                    }
                })
                .create().show();
    }


    /**
     * 使滚动条滚动至指定位置（垂直滚动）
     *
     * @param scrollView 要滚动的ScrollView
     * @param to         滚动到的位置
     */
    protected void scrollVertical(final ScrollView scrollView, final int to) {
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, to);
            }
        }, 100);
    }

    /**
     * 使ScrollView滚动至底部，显示Submit按钮
     *
     * @param scrollView 要滚动的scrollView
     */
    protected void scrollToShowSubmitBtn(final ScrollView scrollView) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollVertical(scrollView, scrollView.getHeight());
            }
        }, 200);
    }

}
